# -*- coding: utf-8 -*-
from datetime import timedelta, datetime

from odoo import models, fields, api


class HrAttendanceRow(models.Model):
    _name = 'hr.attendance.row'
    employee_id = fields.Many2one('hr.employee', string='员工')
    check_time = fields.Datetime(string=u'打卡时间')
    attendance_type = fields.Selection([
        ('i', '上班'),
        ('o', '下班'),
    ], string=u'类别')
    date = fields.Date(string=u'日期', required=True)


class HRecord(models.Model):
    _name = 'hr.record'
    _description = u'打卡记录'
    _order = 'card_date_time desc'
    record_id = fields.Char(string='ID', index=True)
    card_id = fields.Char(string=u'考勤编号', index=True)
    card_date_time = fields.Datetime(string=u'打卡时间', index=True,required=True)
    show_card_date_time = fields.Datetime(string=u'打卡时间', compute='compute_show_card_date_time',store=True,index=True)
    attendance_id = fields.Many2one('hr.attendance', index=True)

    @api.depends('card_date_time')
    def compute_show_card_date_time(self):
        for r in self:
            if r.card_date_time:
                r.show_card_date_time = r.card_date_time + timedelta(hours=-8)
            else:
                r.show_card_date_time=''

    machine_id = fields.Char(string='机器号', index=True)
    emp_id = fields.Char(string=u'员工ID', index=True)
    date = fields.Date(compute='compute_date_for_attendance')

    def compute_date_for_attendance(self):
        for r in self:
            if r.employee_id and r.employee_id.get_current_calendar_id(
                    r.card_date_time.strftime('%Y-%m-%d')) and r.employee_id.get_current_calendar_id(
                r.card_date_time.strftime('%Y-%m-%d')).calendar_type == '3':
                if r.card_date_time.hour <= 12:
                    r.date = r.card_date_time + timedelta(days=-1)
                else:
                    r.date = r.card_date_time
            else:
                r.date = r.card_date_time

    employee_id = fields.Many2one('hr.employee', compute='compute_employee_id', string=u'员工', store=True)

    @api.depends('emp_id', 'card_id')
    def compute_employee_id(self):
        for r in self:
            e = False
            if r.card_id:
                e = self.env['hr.employee'].search([('pin', '=', r.card_id)])
            elif r.emp_id:
                e = self.env['hr.employee'].search([('barcode', '=', r.emp_id)])
            if e:
                r.employee_id = e.id
            else:
                r.employee_id = False

    def corn_create_or_update_hr_attendance(self):
        now = fields.Date.today()
        this_month_start = datetime(now.year, now.month, 1)- timedelta(days=1)
        print(this_month_start)
        records=self.env['hr.record'].search([('card_date_time','>',this_month_start)])
        print (len(records))
        records.create_or_update_hr_attendance()

    def create_or_update_hr_attendance(self):
        for record in self:
            if record.employee_id:
                attendance_id = self.env['hr.attendance'].search(
                    [('employee_id', '=', record.employee_id.id), ('date', '=', record.date)])
                if not attendance_id:
                    attendance_id = self.env['hr.attendance'].create({
                        'date': record.date,
                        'employee_id': record.employee_id.id
                    })
                record.attendance_id = attendance_id.id
            else:
                record.attendance_id = False

        # for record in self:
        #     if record.employee_id:
        #         attendance_id = self.env['hr.attendance'].search(
        #             [('employee_id', '=', record.employee_id.id), ('date', '=', record.date)])
        #         if not attendance_id:
        #             attendance_id = self.env['hr.attendance'].create({
        #                 'date': record.date,
        #                 'employee_id': record.employee_id.id
        #             })
        #         record.attendance_id = attendance_id.id
        #     else:
        #         record.attendance_id = False


class HRecordnew(models.Model):
    _name = 'hr.record.new'
    """
    原始表
    """
    _description = u'打卡记录'
    _order = 'card_date_time desc'
    record_name = fields.Char(string='ID')
    card_id = fields.Char(string='考勤编号', index=True)
    card_date_time = fields.Datetime(string='打卡时间', index=True)
    record_id = fields.Char( index=True)
    new_record_id=fields.Many2one('hr.record',index=True)

    def update_hr_record(self):
        records = self.env['hr.record.new'].search([('write_uid', '=', False)])
        for record in records:
            record_id = self.env['hr.record'].create({
                'card_id': record.card_id,
                'card_date_time': record.card_date_time
            })
            record.new_record_id = record_id.id

